package org.snow001.lcy;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InvokeServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 7434579405737817041L;
	private static final String INVOKE_KERNEL_SUPPORT_PROVIDER_IMPL = "invoke_kernel_support_provider_impl";
	private static final String RESULT_RESPONSE_IMPL = "result_response_impl";
	private Class invokeKernelSupportProviderClass;
	private Class resultResponseClass;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String className = config.getInitParameter(INVOKE_KERNEL_SUPPORT_PROVIDER_IMPL);
		try {
			invokeKernelSupportProviderClass = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			invokeKernelSupportProviderClass = null;
		}
		className = config.getInitParameter(RESULT_RESPONSE_IMPL);
		try {
			resultResponseClass = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			resultResponseClass = null;
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			InvokeKernelSupportProvider invokeKernelSupportProvider = (InvokeKernelSupportProvider) invokeKernelSupportProviderClass.getConstructor(
					new Class[] { HttpServletRequest.class }).newInstance(new Object[] { request });
			InvokeKernelSupport support = invokeKernelSupportProvider.getInvokeKernelSupport();
			Result result = InvokeKernel.invoke(support);
			ResultResponse resultResponse = (ResultResponse) resultResponseClass.getConstructor(new Class[] { HttpServletResponse.class })
					.newInstance(new Object[] { response });
			resultResponse.response(result);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

}
